import { observable } from 'mobx'
import { apiOption, common } from '../Api'


class RootStore {
  // 登录状态
  @observable
  private _isLogin = false


  @observable
  private _avator?: string

  get isLogin() {
    return this._isLogin
  }

  set isLogin(value: boolean) {
    this._isLogin = value
  }

  get avator() {
    return this._avator ||''
  }

  set avator(avatarurl: string) {
    this._avator = avatarurl
  }
  



  errorHandle(status: number) {
    if (status === 403 && this._isLogin) {
      window.alert('登录已超时，请重新登录')
      this.logout()
    }
  }

  init() {
    const userId = sessionStorage.getItem('userId')
  
    const token = sessionStorage.getItem('token')
    const avatarurl = sessionStorage.getItem('avatarurl')||''
    if (userId  && token) {
      apiOption.setOnError(this.errorHandle)
      apiOption.setCredentials(token, parseInt(userId, 10))
      this._avator = avatarurl 
      this._isLogin = true
    }
  }

  async register(userName: string, password: string){
    const res = await common.register({
      name:userName,
      password
    })
    return res
  }

  async onComment(momentId:number,content:string) {
    const res = await common.onComment({
      momentId,
      content
    })
    return res
  }

  async onCommentOther(zcomid:number|undefined,momentId:number|undefined,content:string) {
    const res = await common.onCommentOther(zcomid,{
      momentId,
      content
    })
    return res
  }
  
  async login(userName: string, password: string) {
    const res = await common.login({
      name: userName,
      password,
    })
    if (res.success && res.data) {
      sessionStorage.setItem('userId', res.data.id.toString())
      sessionStorage.setItem('token', res.data.token)
      sessionStorage.setItem('avatarurl',res.data.avatar_url)
      this.init()
    }
    return res
  }

  logout() {
    sessionStorage.removeItem('userId')
    sessionStorage.removeItem('roleId')
    sessionStorage.removeItem('token')
    sessionStorage.removeItem('avatarurl')
    this._isLogin = false
  }
}

export default RootStore
